package com.sinodata.bsm.cicp.finder.aix;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * Description: AIX 主机发现程序.
 * 程序返回：主机名，CPU核数，OS类型，主机型号，OS版本
 */
public class OS extends AixFinder {
    private static Logger logger = Logger.getLogger(OS.class);
    private static final String SHELL = "uname -aM";

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] osRes = null;
        BufferedReader reader = null;
        String strLine = null;
        String regex = "(\\S+)\\s+(\\S+)\\s+(\\d+)\\s+(\\d+)\\s+\\S+\\s+(.*)";
        Pattern pattern = Pattern.compile(regex);
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    osRes = new String[8];
                    list.add(osRes);
                    osRes[0] = "0"; //资源唯一标示
                    osRes[1] = "OS"; //资源名称
                    osRes[2] = getHostName(ip) + "OS"; //描述
                    osRes[3] = matcher.group(2); //主机名
                    osRes[4] = getCpuNumber(ip) + "";//CPU核数
                    osRes[5] = matcher.group(1); //OS类型
                    osRes[6] = matcher.group(5); //主机型号
                    osRes[7] = matcher.group(4) + "." + matcher.group(3); //OS版本
                }
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to find aix Host", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }

    private int getCpuNumber(String ip) {
        String shell = "pmcycles -m";
        BufferedReader reader = null;
        int cpuNumber = 0;
        try {
            reader = CommandReader.getReader(ip, shell, 0, 0);
            while (reader.readLine() != null) {
                cpuNumber++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cpuNumber;
    }
}
